package tangjl.async.websocket;

import javax.websocket.Session;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * 存储业务定义的sessionId和连接的对应关系
 *
 * @author tangjialin on 2017-12-17.
 */
public class SessionUtils {

    public static Map<String, Session> clients = new ConcurrentHashMap<>();

    public static void put(String uniqueIdentification, Session session) {
        clients.put(uniqueIdentification, session);
    }

    public static Session get(String uniqueIdentification) {
        return clients.get(uniqueIdentification);
    }

    public static void remove(String uniqueIdentification) {
        clients.remove(uniqueIdentification);
    }

    /**
     * 将数据传回客户端
     *
     * @param uniqueIdentification
     * @param message
     */
    public static void broadcast(String uniqueIdentification, String message) {
        Session session = SessionUtils.get(uniqueIdentification);
        if (session != null) {
            session.getAsyncRemote().sendText(message);
        } else {
            throw new NullPointerException(uniqueIdentification + "Connection does not exist");
        }
    }

}